import { Component, OnInit } from '@angular/core';
import { HttpClient} from '@angular/common/http'


@Component({
  selector: 'app-contact-list',
  templateUrl: './contact-list.component.html',
  styleUrls: ['./contact-list.component.css']
})
export class ContactListComponent implements OnInit {
  public contacts:any;
  constructor(
    private http:HttpClient,
  ) { }

  ngOnInit(): void {
    this.getContacts();

  }

  getContacts():void{
    const auth_token = window.localStorage.getItem('auth_token');

    this.http.get('http://localhost:3000/contacts')
    .toPromise()
    .then((data)=> {
      this.contacts = data;
      console.log(this.contacts)
    }).catch(err=>{
      window.alert("获取数据错误")
    })
  }

  deleteContactById(id, e):void{
    // 去除默认的响应事件
    e.preventDefault();
    if(!window.confirm(`你确定删除${id}吗？`))
    {
      return;
    }
    console.log(id)
    this.http.delete(`http://localhost:3000/contacts/${id}`)
    .toPromise()
    .then(data=>{
        // 重新获取数据
        console.log(`${id}删除了`)
        this.getContacts();
    })
    .catch(err=>{
      console.log(err)
    })
  }

}
// 设置请求头
// {headers:new HttpHeaders().set('X-Access-Token', auth_token)}